<template>
  <div>

      <el-dialog
        width="70%"
        :title="textMap[dialogStatus]"
        :visible.sync="DialogFormVisibleCom"
        append-to-body
        >

        <!-- vxe检索数据组件 -->
        <search-form
          ref="searchForm"
          :formSearchData.sync="formSearchData"
          :tableTypeOptions="tableTypeOptions"
          :psTypeOptions="psTypeOptions"
          :tableTypeOptionsfu="tableTypeOptions"
          :isexEditTableFu.sync="isexEditTableFu"
          @formSearchDataTableNameChangeEmit="formSearchDataTableNameChangeEmit"
          @formSearchDataPTableNameChangeEmit="formSearchDataPTableNameChangeEmit"
          @searchEventEmit="searchEventEmit"
        >
        </search-form>

        <!-- 表： -->
        <ex-edit-table
          ref='exEditTable'
          :checkBoxConfigs1="checkBoxConfigs1"
          :tableColumn="tableColumn"
          :tableData="tableData"
          :loading.sync="loading"
          :editRules="editRules"
          >
        
        </ex-edit-table>

        <template v-if="isexEditTableFu">
          <!-- 父表： -->
          <ex-edit-table-fu
            ref='exEditTableFu'
            :tableColumn="tableColumn"
            :tableData="tableDataFu"
            :loading.sync="loadingFu"
            :editRules="editRules"
            >
          
          </ex-edit-table-fu>
        </template>
      </el-dialog>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// import PageHeaderLayout from '@/layouts/PageHeaderLayout'
// import ApeDrawer from '@/components/ApeDrawer'
// import { mapGetters } from 'vuex'
import XEUtils,{ isNaN } from 'xe-utils'
import { filterAllRowBynormData } from '@/utils/index'
// 基础表格组件
import ExEditTable from '@/components/VxeTable/ExEditTableA'

import ExEditTableFu from '@/components/VxeTable/ExEditTableA'

import SearchForm from './SearchForm'


import {
  addtemplatecontent
} from '../../service/baseApi'

export default {
  name: 'AddTableSubmitForm',
  components: {
    ExEditTable,
    SearchForm,
    ExEditTableFu
  },
  props: {
    /* 当前行数据 */
    currentRow: {
      type: Object,
      default() {
        return {}
      }
    },
    dialogFormVisible: {
      type: Boolean,
      default: false
    },
    dialogStatus: {
      type: String,
    },
    tableTypeOptions:{
      type: Array
    },
    tableTypeOptionsfu:{
      type: Array
    },
    psTypeOptions:{
      type: Array
    },
    fieldNameOptions:{
      type: Array
    },
    pFieldNameOptions:{
      type: Array
    },
    checkBoxConfigs1: {
      type: Object,
      default() {
        return {}
      }
    }
    // //期限点编号--待
    // stayTermCodeOptions: {
    //   type: Array
    // },
    // //期限点编号--叠
    // sppstTermCodeOptions: {
    //   type: Array
    // },
    // //期限点编号--合
    // mergeTermCodeOptions: {
    //   type: Array
    // },
  },
  // 定义属性
  data() {
    
    return {
      textMap: {
        update: '修改',
        create: '新增'
      },
      // // 表单数据对象
      // formSubmitData: {
      //   id: undefined,
      //   m_id: "",
      //   merge_term_code: "",
      //   rfr_value: "",
      //   sppst_pct_value: "",
      //   sppst_term_code: "",
      //   stay_pct_value: "",
      //   stay_term_code: "",
      // },
      loading:false,
      loadingFu:false,
      // 检索条件
      formSearchData: {
          table_name: '',
          ps_type: '1',
          p_table_name: '',
      },
      isexEditTableFu:false,

      tableColumn: [
        // { type: 'seq', width: 60 },
        { type: 'checkbox', width: 50 },
        // { field: 'id', width: 160,title: 'ID',visible:false },
        { field: 'column_name', title: '字段名',visible:true },
        { field: 'column_comment', title: '字段备注',visible:true },
        {
          field: 'field_meaning', title: '字段含义', 
          editRender: {
            name: 'ElInput', 
            options: [] ,
            props: { size: 'small', clearable: true },
          }
        },
        // { field: 'is_nullable', title: '是否必填'},
        { field: 'is_nullable', title: '是否必选', width: 300, formatter(obj){
          if (obj.cellValue == "NO") {
            return "必选"
          }else{
            return "非必选"
          }
        } },
        // { title: '操作',fixed:'right', width: 200, slots: { default: 'operate' } }
      ],
      tableData: [
      ],
      tableDataFu:[],
      editRules:{
        field_meaning: [
          { required: true, message: '字段含义不能为空' },
        ],
        // sppst_term_code: [
        //   { required: true, message: '期限点编号-叠,不能为空' },
        // ],
        // merge_term_code: [
        //   { required: true, message: '期限点编号-合,不能为空' },
        // ],
        // stay_pct_value: [
        //   { required: true, message: '值-待,不能为空' },
        // ],
        // sppst_pct_value: [
        //   { required: true, message: '值-叠,不能为空' },
        // ],
        // rfr_value: [
        //   { required: true, message: '参照倍数,不能为空' },
        // ],
        
      }




    }
  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {
    DialogFormVisibleCom: {
      get() {
        return this.dialogFormVisible
      },
      set(val) {
        this.$emit('update:dialogFormVisible', val)
      }
    },
    // formSubmitDataCom: {
    //   get() {
    //     return this.formSubmitData
    //   },
    //   set(val) {
    //     this.$emit('update:formSubmitData', val)
    //   }
    // },
  },
  // 监控data中的数据变化
  watch: {
    // currentRow(dataVal, oldVal){
    //   this.findTCCurveSuperpositionFindTCCurveSuperpositionzi(this.currentRow.id)
    //   this.findTCCurveSuperpositionFindtermCode(dataVal)
    // }
    fieldNameOptions(dataVal, oldVal){
      console.log('dataValdataValdataVal',dataVal);
      this.tableData = dataVal
    },
    pFieldNameOptions(dataVal, oldVal){
      console.log('dataValdataValdataVal',dataVal);
      this.tableDataFu = dataVal
      
        // this.clearPtableData()


        //  const dataValNew = XEUtils.map(dataVal, item => {
        //   return {
        //     column_comment:item.column_comment,
        //     column_name:'pp_' + item.column_name
        //   }
        // }) 

        // console.log(dataValNew);

        // this.tableData = this.tableData.concat(dataValNew)


    }
  },
  // 方法集合
  methods: {
    formSearchDataTableNameChangeEmit(nVal,table_type){
      this.$emit('formSearchDataTableNameChangeEmitEmit',nVal,table_type)
    },
    formSearchDataPTableNameChangeEmit(nVal,table_type){
      this.$emit('formSearchDataPTableNameChangeEmitEmit',nVal,table_type)
    },
    async searchEventEmit(){

      console.log("this.tableData",this.tableData);
       console.log("this.tableDataFu",this.tableDataFu);
       console.log("this.formSearchData",this.formSearchData);
      //  {fullData, visibleData, tableData, footerData}
      //  let { tableData } = this.$refs.exEditTable.$refs.xGrid.getTableData()
      //  let ischenno = XEUtils.find(tableData, item => !this.$refs.exEditTable.$refs.xGrid.isCheckedByCheckboxRow(item) && item.is_nullable==='NO')
      //   if (!XEUtils.isUndefined(ischenno)) {
          
      //   }

      let selectRecords = this.$refs.exEditTable.$refs.xGrid.getCheckboxRecords()

      if (this.isexEditTableFu) {
        let selectRecords2 = this.$refs.exEditTableFu.$refs.xGrid.getCheckboxRecords()
        if (selectRecords.length>0 || selectRecords2.length>0) {
          const errMap = await this.$refs.exEditTable.$refs.xGrid.validate(selectRecords).catch(errMap => errMap)
          const errMapFu = await this.$refs.exEditTableFu.$refs.xGrid.validate(selectRecords2).catch(errMap => errMap)
          if (errMap || errMapFu) {
            this.$message({
                showClose: true,
                message: '校验不通过！',
                type: 'warning'
              });
          }else{
            // 手动清除单元格激活状态
            await this.$refs.exEditTable.$refs.xGrid.clearActived()
            await this.$refs.exEditTableFu.$refs.xGrid.clearActived()

            // 添加数据
            await this.addtemplatecontentApi({
                main:this.formSearchData,
                tableData:XEUtils.map(selectRecords, item =>{
                  return {
                    column_name:item.column_name,
                    column_comment:item.column_comment,
                    field_meaning:item.field_meaning
                  }
                }),
                tableDataFu:XEUtils.map(selectRecords2, item =>{
                  return {
                    column_name:item.column_name,
                    column_comment:item.column_comment,
                    field_meaning:item.field_meaning
                  }
                }),
            })


          }
        }else{
            this.$message({
              showClose: true,
              message: '未选中数据！',
              type: 'warning'
            });
        }
      }else{
        if (selectRecords.length>0) {
          const errMap = await this.$refs.exEditTable.$refs.xGrid.validate(selectRecords).catch(errMap => errMap)
            if (errMap) {
            this.$message({
                showClose: true,
                message: '校验不通过！',
                type: 'warning'
              });
          }else{
            // 手动清除单元格激活状态
            await this.$refs.exEditTable.$refs.xGrid.clearActived()

            // 添加数据
            await this.addtemplatecontentApi({
                main:this.formSearchData,
                tableData:XEUtils.map(selectRecords, item =>{
                  return {
                    column_name:item.column_name,
                    column_comment:item.column_comment,
                    field_meaning:item.field_meaning
                  }
                }),
                tableDataFu:[]
            })

          }
          
        }else{
            this.$message({
              showClose: true,
              message: '未选中数据！',
              type: 'warning'
            });
        }

      }
      



      // console.log("selectRecordsselectRecords",selectRecords);


      // let selectRecords2 = (this.isexEditTableFu)?this.$refs.exEditTableFu.$refs.xGrid.getCheckboxRecords():true
      // let selectRecordsL2 = (this.isexEditTableFu)?selectRecords2.length>0:true
      // if (selectRecords.length>0 || selectRecordsL2) {
      //   // const errMap = await this.$refs.xGrid.validate(row).catch(errMap => errMap)

      //   const errMap = await this.$refs.exEditTable.$refs.xGrid.validate(selectRecords).catch(errMap => errMap)
      //   const errMapFu = await (this.isexEditTableFu)?this.$refs.exEditTableFu.$refs.xGrid.validate(selectRecords2).catch(errMap => errMap):true

      //   if (errMap || errMapFu) {
      //     this.$message({
      //         showClose: true,
      //         message: '校验不通过！',
      //         type: 'warning'
      //       });
      //   }else{
      //       // 手动清除单元格激活状态
      //       await this.$refs.exEditTable.$refs.xGrid.clearActived()
      //       await this.$refs.exEditTableFu.$refs.xGrid.clearActived()

      //       // 添加数据
      //       await this.addtemplatecontentApi({
      //           main:this.formSearchData,
      //           tableData:XEUtils.map(selectRecords, item =>{
      //             return {
      //               column_name:item.column_name,
      //               column_comment:item.column_comment,
      //               field_meaning:item.field_meaning
      //             }
      //           }),
      //           tableDataFu:XEUtils.map(selectRecords2, item =>{
      //             return {
      //               column_name:item.column_name,
      //               column_comment:item.column_comment,
      //               field_meaning:item.field_meaning
      //             }
      //           }),
      //       })




          

      //   }

      // }else{
      //   this.$message({
      //     showClose: true,
      //     message: '未选中数据！',
      //     type: 'warning'
      //   });
      // }
      // console.log(selectRecords2);
      // const errMap = await this.$refs.xGrid.validate(row).catch(errMap => errMap)
      // if (errMap) {
      //    this.$message({
      //     showClose: true,
      //     message: '校验不通过！',
      //     type: 'warning'
      //   });
      //   // this.$XModal.message({ status: 'error', message: '校验不通过！' })
      // } else {
      //   await this.$refs.xGrid.clearActived().then(() => {
      //     this.$emit('saveRowEventEmit', row)
      //   })
      // }

      // await this.addtemplatecontentApi({

      // })


    },
    addtemplatecontentApi({main,tableData,tableDataFu}){
      addtemplatecontent({
        m_id:this.currentRow.id,
        ...main,
        tableData,
        tableDataFu
      }).then(() => {
        this.$emit("reloadfindList")
      })
    },
    // clearPtableData(){
    //   console.log("删除开头为");
    //     // 初始化-删除开头为"term_"的元素
    //      console.log('this.tableDatathis.tableData',this.tableData);
    //   XEUtils.objectEach(this.tableData, (item, key) => {
       
    //     if (item.column_name.startsWith("pp_")) {
    //       // delete this.formSubmitData[`${key}`];
    //       this.$delete(this.tableData, key)
    //       console.log(`this.tableData[${key}]`, key);
    //     }
    //   })
    // },
    /**
     * 过滤表单提交之外的数据（返回新数组）
     */
    // filterFormSubmitDataExcept(obj){
    //   let f,allRow
    //   if (XEUtils.isEmpty(obj.allRow) || XEUtils.isEmpty(obj.formSubmitData)) {
    //     return []
    //   }
    //   allRow = obj.allRow
    //   f = obj.formSubmitData

    //   XEUtils.objectEach (allRow, (item, key) => {
    //     if (!f.hasOwnProperty(key)) {
    //       delete allRow[`${key}`]
    //     }
    //   })
    //   return allRow
    // },
    // async saveRowEventEmit(row){

    //   if (XEUtils.isEmpty(row.id)) {
    //     await addTCCurveSuperpositionzi({
    //       ...row,
    //       m_id:this.currentRow.id
    //     }).then(({data}) => {

    //     }, error => {
    //       console.log('getList:error', error);
    //     })

    //   }else{
        
    //     // 排除FormSubmitData没有的元素
    //     row = filterAllRowBynormData({
    //       allRow: XEUtils.clone(row, true),
    //       normData:this.formSubmitData
    //     })
        
    //     await updateTCCurveSuperpositionzi({
    //       ...row,
    //       m_id:this.currentRow.id
    //     }).then(({data}) => {

    //     }, error => {
    //       console.log('getList:error', error);
    //     })
    //   }
      

    //   await this.findTCCurveSuperpositionFindTCCurveSuperpositionzi(this.currentRow.id)

    //   await this.$emit('handleFindListEmit')

    //   console.log('saveRowEventEmitsaveRowEventEmit',row);
    //   console.log('removeRowEventEmitremoveRowEventEmit-mid',this.currentRow.id);
    // },
    // removeRowEventEmit(row){

    //   deleteTCCurveSuperpositionzi({
    //     id:row.id
    //   }).then(({data}) => {
    //     this.$refs.exEditTable.$refs.xGrid.remove(row)
    //   })
    //   // console.log('removeRowEventEmitremoveRowEventEmit',row);
    //   // console.log('removeRowEventEmitremoveRowEventEmit-mid',this.currentRow.id);
    // },
    /* 点击编辑按钮 */
    // editRowEventEmit(row){
    //   // 当前行开启编辑模式
    //   this.$refs.exEditTable.$refs.xGrid.setActiveRow(row)
    // },

    // findTCCurveSuperpositionFindtermCode(row){
    //   // 待
    //   tCCurveSuperpositionFindtermCode({
    //     type:row.stay_type,
    //     s_date:row.s_date,
    //     e_date:row.e_date,
    //     cv_code:row.stay_curve_code
    //   }).then(({data}) => {
    //     const stay_term_code_column = this.$refs.exEditTable.$refs.xGrid.getColumnByField('stay_term_code')
    //     stay_term_code_column.editRender.options = XEUtils.map(data.rows, item =>{
    //       return {
    //         label:item.term_name,
    //         value:item.term_code
    //       }
    //     })
    //   })
    //   // 叠
    //   tCCurveSuperpositionFindtermCode({
    //     type:row.sppst_type,
    //     s_date:row.s_date,
    //     e_date:row.e_date,
    //     cv_code:row.sppst_curve_code
    //   }).then(({data}) => {

    //     const merge_term_code_column = this.$refs.exEditTable.$refs.xGrid.getColumnByField('merge_term_code')
    //     merge_term_code_column.editRender.options = XEUtils.map(data.rows, item =>{
    //       return {
    //         label:item.term_name,
    //         value:item.term_code
    //       }
    //     })
    //   })
    //   // 合
    //   tCCurveSuperpositionFindtermCode({
    //     type:row.merge_type,
    //     s_date:row.s_date,
    //     e_date:row.e_date,
    //     cv_code:row.merge_curve_code
    //   }).then(({data}) => {
    //     const sppst_term_code_column = this.$refs.exEditTable.$refs.xGrid.getColumnByField('sppst_term_code')
    //     sppst_term_code_column.editRender.options = XEUtils.map(data.rows, item =>{
    //       return {
    //         label:item.term_name,
    //         value:item.term_code
    //       }
    //     })
    //   })
    // },
    // /* 查询 期限字符串列表   参数 m_id */
    // findTCCurveSuperpositionFindTCCurveSuperpositionzi(m_id){
    //   this.loading = true
    //   tCCurveSuperpositionFindTCCurveSuperpositionzi({
    //     m_id
    //   }).then(({data}) => {
    //     this.tableData = data.rows
    //     // 关闭加载特效
    //     setTimeout(() => {
    //       this.loading = false
    //     }, 0.5 * 1000)
    //   })
    // },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {

  // this.$set(this.formSearchData,'table_name',"")
  // this.$set(this.formSearchData,'ps_type',"")
  // this.$set(this.formSearchData,'p_table_name',"")

    // console.log('currentRowcurrentRow',this.currentRow);
    // this.findTCCurveSuperpositionFindTCCurveSuperpositionzi(this.currentRow.id)
    // // 获取期限字符串选项
    // this.findTCCurveSuperpositionFindtermCode(this.currentRow)

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
        // console.log('columncolumncolumnco3lumn',this.$refs.exEditTable);
  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang='scss' scoped>
  
</style>